import * as xin from '../index';

$(function() {
	// get url address
	function resolveUri(othis, target) {
		return othis.attr('href') || othis.attr('url') || othis.attr('action') || othis.data('url')
			|| target.attr('action') || target.attr('href') || target.attr('url') || target.data('url');
	}

	// build target options
	function buildOptions(othis, controlName) {
		return $.extend({
			confirm: true,
			confirmContent: '你确定要执行此操作吗？',
			mustTargetQuery: false,
			notTargetQueryMsg: '没有任何数据！',
			replaceParam: false,
			refresh: true,
			onData: null
		}, xin.getDataOptions(othis, controlName));
	}

	// 执行操作
	function handler() {
		const othis = $(this),
			controlName = xin.getControlName(this, "ajaxGet,ajaxPost");

		// build target options
		const options = buildOptions(othis, controlName);

		// get a target jquery object.
		const target = $(options.target);

		// get url address
		const url = resolveUri(othis, target);
		if (!url) {
			console.error(othis.text() + "中使用ajax，请确保url 不能为空");
			return false;
		}

		// if support validator the verify whether it is correct
		if (xin.isSupportFormValidator() && target.get(0).tagName.toLowerCase() === "form") {
			const formValidOptions = othis.data('validator');
			if (!xin.formValid(formValidOptions))
				return false;
		}

		// execute ajax
		const ajaxActuator = makeAjaxActuator(
			url, othis, target,
			controlName, options
		);

		// if show confirm modal the click ok button after exec request
		if (options.confirm) {
			// fix layui select
			const oldValue = othis[0].oldValue;
			xin.showModal({
				content: options.confirmContent,
				showCancel: true
			}).then(function(res) {
				if (res.cancel) {
					updateLayuiRender(othis, oldValue);
					return;
				}

				ajaxActuator();
			});
		} else { // right away exec request
			ajaxActuator();
		}
	}

	// 更新渲染layui.form
	function updateLayuiRender(othis, oldValue) {
		// if (!othis.attr('lay-skin')) {
		// 	return;
		// }

		let type = "select";
		if ('INPUT' === othis.prop("tagName")) {
			othis.prop('checked', !othis.prop('checked'));
			type = "checkbox";
		} else if ('SELECT' === othis.prop("tagName")) {
			if (oldValue !== undefined) {
				othis.val(oldValue);
			}
		}

		const filter = othis.closest('.layui-form').attr('lay-filter');
		layui.form.render(type, filter);
	}


	// 获取执行器
	function makeAjaxActuator(url, othis, target, controlName, options) {
		// is get request
		const isGet = "ajaxGet" === controlName;

		// elem state
		const elemStateActuator = makeElemStateActuator(othis);

		const isFormElem = function() {
			return ['INPUT', 'SELECT'].indexOf(othis.prop("tagName")) !== -1;
		};

		return function() {
			const method = isGet ? "GET" : "POST";

			// 检查是否有请求参数回调器
			let params = options.onRequest ? options.onRequest.call(othis) : '';
			if (typeof params !== 'string') {
				params = $.param(params);
			}

			// 如果是form元素 则检查name属性
			if (isFormElem()) {
				const fieldName = othis.attr('name');
				if (fieldName) {
					params += (!params || params.charAt(params.length - 1) === "&" ? "" : "&") + fieldName + "=" + encodeURIComponent(othis.val());
				}
			}

			// 03 13 18 23 31    04 07

			// 是否是替换现有参数，如果不是则是追加参数
			if (options.replaceParam !== true) {
				const targetParam = target.serialize();
				if (targetParam !== "") {
					params = targetParam + "&" + params;
				}
			}

			// 如果参数为空并且要求必须有参数时，则提示错误信息
			if (!params && options.mustTargetQuery) {
				xin.showModal({
					icon: 'error',
					content: options.notTargetQueryMsg
				});
				return;
			}

			// disable elem state.
			elemStateActuator.disabled();

			// async request server
			xin.request({
				url: url,
				type: method,
				data: params,
			}).then((res) => {
				othis.trigger('success', [res]);

				// 是否存在模板编译字符串
				if (options.template) {
					const template = $(options.template);
					const templateDist = $(options.templateDist || othis);

					const content = xin.tpl({
						template: template.html(),
						data: res.data
					});

					templateDist.html(content);
				} else if (options.refresh !== false) { // 是否需要刷新浏览器
					setTimeout(function() {
						if (res.url) {
							location.href = res.url;
						} else {
							location.reload();
						}
					}, 1000);//res.wait ? res.wait * 1000 : 1000
				}

			}, (err) => {
				othis.trigger('error', [err]);
			}).always(() => {
				elemStateActuator.enable();
			});
		}
	}

	// 获取元素状态
	function makeElemStateActuator(target) {
		return {
			// statement propDisabled function Used to disable button
			disabled() {
				target.addClass('disabled btn-disabled layui-btn-disabled').prop('disabled', true);
			},

			// statement propEnable function User to enable button
			enable() {
				target.removeClass('disabled btn-disabled layui-btn-disabled').prop('disabled', false);
			}
		};
	}

	//ajax config
	$(document).on('click change blur', '[data-ajax-get],[data-ajax-post]', function(e) {
		if (e.type === 'focusout' && !this.dataset.enableFocus) {
			return false;
		}

		xin.safeCallback(this, handler);

		return false;
	});
});
